import re

from flask import request, session, redirect
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import login_required, current_user, login_user, logout_user

from api.db.services.knowledgebase_service import KnowledgebaseService
from api.utils.api_utils import server_error_response, validate_request
from api.utils import get_uuid, get_format_time, decrypt, download_img, current_timestamp, datetime_format
from api.db import UserTenantRole, LLMType, FileType
from api.settings import RetCode
from api.db.services.user_service import UserService, TenantService, UserTenantService, UserKnowledgeService
from api.settings import stat_logger
from api.utils.api_utils import get_json_result, cors_reponse


def encrypt_password(encrypted_password: str) -> str:
    """
    解密并加密密码
    :param encrypted_password: 加密后的密码字符串
    :return: 加密存储的密码哈希
    """
    decrypted_password = decrypt(encrypted_password)
    hashed_password = generate_password_hash(decrypted_password)
    return hashed_password


@manager.route("/add_user", methods=["POST"])
@login_required
@validate_request("nickname", "email", "password", "role", "knowledge_details")
def admin_add_user():
    req = request.json
    # 检查用户是否已存在
    if UserService.query(email=req["email"]):
        return get_json_result(
            data=False, retmsg=f'Email: {req["email"]} has already registered!', retcode=RetCode.OPERATING_ERROR)

    # 检查邮箱格式是否有效
    if not re.match(r"^[\w\._-]+@([\w_-]+\.)+[\w-]{2,4}$", req["email"]):
        return get_json_result(data=False, retmsg=f'Invalid e-mail: {req["email"]}!',
                               retcode=RetCode.OPERATING_ERROR)
    user_id = get_uuid()
    user_dict = {
        "id": user_id,
        "access_token": get_uuid(),
        "email": req["email"],
        "nickname": req["nickname"],
        "password": decrypt(req["password"]),  # 使用新函数
        "login_channel": "password",
        "last_login_time": get_format_time(),
        "is_superuser": False,  # 新用户默认为非超级用户
    }

    tenant_id = current_user.tenant_id

    usr_tenant = {
        "tenant_id": tenant_id,
        "user_id": user_id,
        "invited_by": current_user.id,  # 记录邀请人的 ID
        "role": req["role"]  # 默认角色为成员
    }

    usr_knowledge = []

    try:
        # 创建用户
        if not UserService.save(**user_dict):
            raise Exception('Failed to create user.')

        # 创建用户与租户的关联
        if not UserTenantService.insert(**usr_tenant):
            raise Exception('Failed to create user-tenant relation.')

        # 创建用户与知识库的关联
        for knowledgebase_id in req["knowledge_details"]:
            usr_knowledge.append({
                "user_id": user_id,
                "knowledgebase_id": knowledgebase_id,
            })
            if not UserKnowledgeService.insert(**usr_knowledge[-1]):
                raise Exception('Failed to create user-knowledge relation.')
        return get_json_result(data=True, retmsg='User added successfully!')
    except Exception as e:
        stat_logger.exception(e)
        return get_json_result(
            data=False, retmsg='User registration failure!', retcode=RetCode.EXCEPTION_ERROR)


@manager.route("/update_user", methods=["POST"])
@login_required
@validate_request("user_id", "nickname", "email", "role", "knowledge_details")
def admin_update_user():
    req = request.json
    user_id = req["user_id"]
    # 查找要修改的用户
    user = UserService.query(id=user_id)[0]
    if not user:
        return get_json_result(
            data=False, retmsg=f'User ID: {user_id} not found!', retcode=RetCode.OPERATING_ERROR)

    # 检查邮箱格式是否有效
    if not re.match(r"^[\w\._-]+@([\w_-]+\.)+[\w-]{2,4}$", req["email"]):
        return get_json_result(data=False, retmsg=f'Invalid e-mail: {req["email"]}!',
                               retcode=RetCode.OPERATING_ERROR)
    user_tenant = UserTenantService.query(user_id=user_id, tenant_id=current_user.tenant_id)[0]
    try:
        # 更新用户信息
        user.nickname = req["nickname"]
        user.email = req["email"]
        if "password" in req:
            user.password = encrypt_password(req["password"])  # 使用新函数
        user.last_login_time = get_format_time()
        user.save()
        # 更新用户与租户的关联
        UserTenantService.update_by_id(user_tenant.id, {"role": req["role"]})

        # 更新用户与知识库的关联
        UserKnowledgeService.delete_by_user_id(user_id)
        for knowledgebase_id in req["knowledge_details"]:
            UserKnowledgeService.insert(user_id=user_id, knowledgebase_id=knowledgebase_id)

        return get_json_result(data=True, retmsg='User updated successfully!')
    except Exception as e:
        stat_logger.exception(e)
        return get_json_result(
            data=False, retmsg='User update failure!', retcode=RetCode.EXCEPTION_ERROR)


@manager.route("/delete_user", methods=["POST"])
@login_required
@validate_request("user_id")
def admin_delete_user():
    req = request.json
    user_id = req["user_id"]

    try:
        # 删除用户与知识库的关联
        UserKnowledgeService.delete_by_user_id(user_id)

        # 删除用户与租户的关联
        UserTenantService.delete_by_user_id_and_tenant_id(user_id=user_id, tenant_id=current_user.tenant_id)
        # 删除用户
        UserService.delete_user(user_ids=user_id)

        return get_json_result(data=True, retmsg='User deleted successfully!')
    except Exception as e:
        stat_logger.exception(e)
        try:
            UserKnowledgeService.rollback_delete_by_user_id(user_id)
            UserTenantService.rollback_delete_by_user_id_and_tenant_id(user_id=user_id,
                                                                       tenant_id=current_user.tenant_id)
            UserService.rollback_delete_user(user_ids=user_id)
        except Exception as e:
            stat_logger.exception("回滚出错：", e)
        return get_json_result(
            data=False, retmsg='User deletion failure!', retcode=RetCode.EXCEPTION_ERROR)


@manager.route("/get_user", methods=["GET"])
@login_required
def admin_get_user():
    # print("进入 /get_user 路由")
    # 获取当前用户的 ID
    current_user_id = current_user.id
    if current_user.user_tenant["role"] == UserTenantRole.ADMIN.value:
        current_user_id = current_user.tenant_id
    # print(f"当前用户ID: {current_user_id}")

    try:
        # 根据当前用户的 ID 获取所有与之相关的 user_id 和 role
        user_tenants = UserTenantService.query(tenant_id=current_user_id)
        # print(f"查询到的用户租户信息: {user_tenants}")

        if not user_tenants:
            print(f"未找到租户ID为 {current_user_id} 的用户")
            return get_json_result(
                data=False, retmsg=f'No users found for tenant ID: {current_user_id}', retcode=RetCode.OPERATING_ERROR)

        # 收集所有 user_id 和 role
        user_data_list = []
        for ut in user_tenants:
            if ut.user_id == current_user_id:
                continue
            if ut.role == UserTenantRole.OWNER:
                continue
            if ut.invited_by != current_user.id and current_user.user_tenant["role"] != UserTenantRole.OWNER:
                continue
            user_id = ut.user_id
            role = ut.role
            # print(f"处理用户ID: {user_id}, 角色: {role}")

            # 根据 user_id 获取用户信息
            user = UserService.get_by_id(user_id)[1]
            # print(f"用户信息: {user}")
            if not user:
                print(f"未找到ID为 {user_id} 的用户")
                continue
            if user.to_json()["status"] != "1":
                continue
            # print(user)
            # 转换用户信息为 JSON 格式，并添加 role 信息
            user_data = user.to_json()

            user_data["role"] = role
            # print(f"用户数据: {user_data}")

            # 根据 user_id 获取 knowledgebase_id
            knowledge_ids = UserKnowledgeService.get_knowledge_ids_by_user_id(user.id)
            # print(f"用户ID {user.id} 关联的知识库ID: {knowledge_ids}")

            if knowledge_ids:
                # 根据 knowledgebase_id 获取知识库的详细信息
                knowledge_details = KnowledgebaseService.query_in_knowledge_ids(knowledge_ids)
                # print(f"知识库ID {knowledge_ids} 详细信息: {knowledge_details}")
                if knowledge_details:
                    user_data["knowledge_details"] = [k.to_json() for k in knowledge_details]
                    # print(f"知识库详细信息: {user_data['knowledge_details']}")
                else:
                    print(f"用户ID {user.id} 无关联的知识库详细信息")
            else:
                print(f"用户ID {user.id} 无关联的知识库ID")

            # 添加用户数据到列表中
            user_data_list.append(user_data)

        return get_json_result(data=user_data_list, retmsg='Users retrieved successfully!')
    except Exception as e:
        print(f"发生异常: {e}")
        stat_logger.exception(e)
        return get_json_result(
            data=False, retmsg='Failed to retrieve users!', retcode=RetCode.EXCEPTION_ERROR)
